package com.javaspeak.concurrency.pattern.application;

import java.math.BigDecimal;

import org.apache.log4j.Logger;

import com.javaspeak.concurrency.pattern.actor.AbstractActor;
import com.javaspeak.concurrency.pattern.actor.ActorRegistry;
import com.javaspeak.concurrency.pattern.actor.ActorRegistryImpl;

public class ProcessTradeActorImpl extends AbstractActor
    implements ProcessTradeActor {

    public Logger logger = Logger.getLogger( ProcessTradeActorImpl.class );

    private boolean isValid( Trade trade ){

        BigDecimal[] result =
            trade.getAmount().divideAndRemainder( new BigDecimal( 7 ) );

        if ( result[ 1 ].compareTo( new BigDecimal( 0 ) ) == 1 ){

            return true;
        }

        return false;
    }

    public void processTrade( Trade trade ){

        logger.debug( "Processing trade with id: " + trade.getTradeId() );

        ActorRegistry actorRegistry = ActorRegistryImpl.getInstance();

        StartActor startActor =
            ( StartActor )actorRegistry.getActor(
                    StartActor.class );

        TradeConfirmation tradeConfirmation;

        if ( isValid( trade ) ){

            tradeConfirmation = new TradeConfirmation( trade, true  );
        }
        else {

            tradeConfirmation = new TradeConfirmation( trade, false );
        }

        startActor.addTradeConfirmation( tradeConfirmation );
    }
}
